package com.yj.apiback.jwt;

import com.yj.apiback.security.SecUser;
import com.yj.apiback.util.ServletUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;

@Service
public class JwtUserDetailsService implements UserDetailsService {
    @Resource
    private PasswordEncoder passwordEncoder;
    /*
    * 说明：这里只是进行演示，把用户写死了，
    * 生产环境中此处的用户名/密码/角色应该是从数据库中查询得到
    * */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("-----loadUserByUsername");
        if (username.equals("lhd") == false) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        //return new User(username, passwordEncoder.encode("123456"), AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));

        //给用户增加用户id和昵称
        String encodedPassword = passwordEncoder.encode("123456");

        Collection<GrantedAuthority> collection = new ArrayList<>();//权限集合
        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
        collection.add(grantedAuthority);

        SecUser user = new SecUser(username,encodedPassword,collection);
        user.setUserid(1);
        user.setNickname("老刘");
        user.setHeadUrl("https://imgs-qn.iliangcang.com/ware/userhead/orig/3/356/689/356689299.jpg");

        //得到登录时所在的域
        String serverName = ServletUtil.getRequest().getServerName();

        //设置所在的域
        user.setDomain(serverName);
        return user;
    }
}